<?php if ( ! defined('APPPATH')) exit('No direct script access allowed');
/**
 *      [PinTuXiu] (C)2001-2099 ONightjar.com Pintuxiu.com.
 *      This is NOT a freeware, use is subject to license terms
*/
include_once APPPATH.'modules/social/OAuth_Sina.php';
class sina_api{
	
	private $vendor='sina';
	private $pz;
	protected $oauth;
	protected $client;
	protected $info;
	function __construct(){
		$socialapis = load_api('setting')->getSetting('socialapi');
		$this->info = $socialapis['sina'];
		$this->pz = &get_instance();
		$this->oauth = new SaeTOAuthV2($this->info['appkey'], $this->info['appsecret']);
	}

	function getloginpage($state=NULL,$display=NULL){
		return $this->oauth->getAuthorizeURL($this->info['callback'],'code',$state,$display);
	}

	function get_accesstoken(){
		if(isset($_REQUEST['code'])){
			
			$token = array();
			$keys = array();
			$keys['code'] = $_REQUEST['code'];
			$keys['redirect_uri'] = $this->info['callback'];
			$temp = $this->oauth->getAccessToken('code',$keys);
			$social_vendor_info = 'social_'.$this->vendor.'_info';
			$this->info['access_token'] = $temp['access_token'];
			return $temp['access_token'];
		}
		return NULL;
	}
	
	function get_userinfo(){
		if(!empty($this->info['access_token'])){
			$userinfo = array();
			$this->client = new SaeTClientV2($this->info['appkey'], $this->info['appsecret'], $this->info['access_token']);
			$array_uid = $this->client->get_uid();
			$temp = $this->client->show_user_by_id($array_uid['uid']);
			$userinfo['uid'] = $array_uid['uid'];
			$userinfo['screen_name'] = $temp['screen_name'];
			$userinfo['name'] = $temp['name'];
			$userinfo['avatar'] = $temp['profile_image_url'];
			$userinfo['location'] = $temp['location'];
			$userinfo['description'] = $temp['description'];
			$userinfo['url'] = $temp['url'];
			if($temp['gender']=='m'){
				$userinfo['gender'] = 'male';
			}elseif ($temp['gender']=='f'){
				$userinfo['gender'] = 'female';
			}else{
				$userinfo['gender'] = 'none';
			}
			return $userinfo;
		}
		return null;
	}
}
